<template>
  <div class="picture-book-page" @click.stop>
    <div class="book_top">
      <!-- <div class="book_top_name">电子画册</div> -->
      <el-button type="primary" class="book_top_add" @click="addBook()">新增</el-button>
    </div>
    <div class="table_box">
      <el-table v-loading="state.dataListLoading" :data="state.dataList" border @selection-change="state.dataListSelectionChangeHandle" style="width: 100%">
        <el-table-column align="center" prop="id" label="序号"  show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="bookName" label="画册名称" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="ifValid" label="状态"  show-overflow-tooltip>
          <template v-slot="scope">
            <span v-if="scope.row.ifValid === 1" style="color: #f56c6c">下架</span>
            <span v-else-if="scope.row.ifValid === 0" style="color: #67c23a">上架</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="createBy" label="创建人"  show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="createAt" label="创建时间"  show-overflow-tooltip></el-table-column>
        <el-table-column align="center" prop="updateAt" label="修改时间"  show-overflow-tooltip></el-table-column>

        <el-table-column align="center" label="操作" width="260">
          <template #default="scope">
            <el-button style="width: 40px" type="primary" @click="handleView(scope.$index, scope.row)" text> 查看 </el-button>
            <el-button style="width: 40px" type="primary" @click="handleEdit(scope.$index, scope.row)" text> 编辑 </el-button>
            <el-button style="width: 40px" class="shanchu" type="danger" @click="handleDelete(scope.$index, scope.row)" text> 删除 </el-button>
            <el-button
              v-if="scope.row.ifValid === 1"
              style="width: 40px"
              type="primary"
              @click="
                handleVoild(scope.$index, scope.row);
                visible = !scope.row.ifValid;
              "
              text
            >
              上架
            </el-button>
            <el-button
              v-else-if="scope.row.ifValid === 0"
              style="width: 40px"
              type="primary"
              @click="
                handleVoild(scope.$index, scope.row);
                visible = !scope.row.ifValid;
              "
              text
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination :current-page="state.page" :page-sizes="[10, 20, 50, 100]" :page-size="state.limit" :total="state.total" layout="total, sizes, prev, pager, next, jumper" @size-change="state.pageSizeChangeHandle" @current-change="state.pageCurrentChangeHandle"> </el-pagination>
    </div>
    <div class="add_book" v-if="popupAdd" @click.stop>
      <div class="pop_up">
        <div class="pop_up_top">
          <!-- <div class="pop_up_left"></div> -->
          <div class="pop_up_name">新增电子画册</div>
          <!-- <div class="pop_up_right"></div> -->
          <!-- 右上角叉号 -->
          <el-button class="top_right" @click="popupAdd = false" type="text">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="pop_up_info">
          <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
            <el-form-item label="画册名称" prop="bookName">
              <el-input v-model="dataForm.bookName" show-word-limit maxlength="30" placeholder="请输入" style="width: 280px"> </el-input>
            </el-form-item>
            <el-form-item label="上传文件" prop="bookUrl">
              <el-upload :action="uploadUrl" :file-list="fileList" :before-upload="beforeUploadHandle" :on-success="successHandle" :on-error="uploadErrorHandle" :limit="1" :show-file-list="true" class="brand-upload">
                <div class="upload-box">
                  <img v-if="!dataForm.bookUrl" src="../../assets/images/file-upload.png" alt="上传图标" class="icon" />
                  <el-image v-else :src="dataForm.imgUrl" fit="cover" class="uploaded-image" @error="handleImageError" />
                </div>
                <template v-slot:tip>
                  <div class="el-upload__tip">
                    {{ "请上传不超过50M的PDF的文件" }}
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-form>

          <div class="operation">
            <el-button type="primary" @click="popupAdd = false" plain>取消</el-button>
            <el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="add_book" v-if="popupInfo" @click.stop>
      <div class="pop_up">
        <div class="pop_up_top">
          <!-- <div class="pop_up_left"></div> -->
          <div class="pop_up_name">电子画册详情</div>
          <!-- <div class="pop_up_right"></div> -->
          <!-- 右上角叉号 -->
          <el-button class="top_right" @click="popupInfo = false" type="text">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="pop_up_info">
          <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
            <el-form-item label="画册名称" prop="bookName">
              <span>{{ dataForm.bookName }}</span>
              <!-- <el-input v-model="dataForm.bookName" show-word-limit maxlength="30" placeholder="请输入" style="width: 280px"> </el-input> -->
            </el-form-item>
            <el-form-item label="上传文件" prop="bookUrl">
              <div class="upload-box">
                <el-image :src="dataForm.imgUrl" @click="onLook()" fit="cover" class="uploaded-image" @error="handleImageError" />
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="add_book" v-if="popupDel" @click.stop>
      <div class="pop_up pop_up_del">
        <div class="pop_up_del_top">
          <div class="pop_up_name">删除电子画册</div>
          <!-- 右上角叉号 -->
          <el-button class="top_right" @click="popupDel = false" type="text">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="pop_up_del_info">
          <div class="del_info">
            <el-icon class="del_info_icon"><WarningFilled /></el-icon>
            <!-- <img class="close_icon" src="@/assets/images/attention.png" alt="" /> -->
            确定删除当前画册吗？
          </div>

          <div class="operation">
            <el-button type="primary" @click="popupDel = false" plain>取消</el-button>
            <el-button type="primary" @click="delBook()">确定</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="add_book" v-if="popupVoild" @click.stop>
      <div class="pop_up pop_up_del">
        <div class="pop_up_del_top">
          <div class="pop_up_name" v-if="visible">是否下架画册</div>
          <div class="pop_up_name" v-else>是否上架画册</div>
          <!-- 右上角叉号 -->
          <el-button class="top_right" @click="popupVoild = false" type="text">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        <div class="pop_up_del_info">
          <div v-if="visible" class="del_info">
            <el-icon class="del_info_icon"><WarningFilled /></el-icon>
            是否下架画册
          </div>
          <div v-else class="del_info">
            <el-icon class="del_info_icon"><WarningFilled /></el-icon>
            是否上架画册
          </div>

          <div class="operation">
            <el-button type="primary" @click="popupVoild = false" plain>取消</el-button>
            <el-button type="primary" @click="VoildBook()">确定</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import app from "@/constants/app";
import { onMounted, reactive, ref, toRefs, nextTick, onActivated } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { IObject } from "@/types/interface";
import { ElMessage,FormRules } from "element-plus";
import type { ComponentSize } from "element-plus";
import useView from "@/hooks/useView";

const { t } = useI18n();
const currentPage4 = ref(4);
const uploadUrl = ref("");
const fileList = ref<IObject[]>([]);

const pageSize4 = ref(100);

const size = ref<ComponentSize>("default");
const background = ref(false);
const disabled = ref(false);
const popupAdd = ref(false);
const popupInfo = ref(false);
const popupDel = ref(false);
const popupVoild = ref(false);
const view = reactive({
  getDataListURL: "/noc/nocsamplebook/page",
  getDataListIsPage: true,
  deleteURL: "/noc/nocsamplebook/delete",
  deleteIsBatch: true
});
const state = reactive({ ...useView(view), ...toRefs(view) });
state.limit = 20;

interface User {
  id: string;
  bookName: string;
  bookUrl: string;
  imgUrl: string;
  size: string;
  ifValid:number
}
const dataFormRef = ref();
const visible = ref(false);
const dataForm = reactive({
  id: "",
  bookName: "",
  bookUrl: "",
  imgUrl: "",
  bookSize: ""
});

const rules: FormRules = {
  bookName: [{ required: true, message: t("validate.required"), trigger: "blur" }],
  bookUrl: [{ required: true, message: t("validate.required"), trigger: "change" }]
};

const onLook = () => {
  console.log(dataForm.bookUrl)
  window.open(dataForm.bookUrl,'_blank')
};
// 上传之前
const beforeUploadHandle = (file: IObject) => {
  if (file.type !== "application/pdf") {
    ElMessage.error(t("upload.tip", { format: "pdf" }) || "只能上传pdf文件");
    return false;
  }
  // 限制图片大小为 2MB
  const maxSize = 50 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.error("上传的图片大小不能超过 50MB，请重新选择！");
    return false;
  }

  return true;
};
// 图片加载错误
const handleImageError = () => {
  ElMessage.error("加载失败");
};
// 上传成功
const successHandle = (res: IObject, file: IObject) => {
  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }

  // 设置图片URL
  dataForm.bookUrl = res.url.pdfUrl;
  dataForm.imgUrl = res.url.imgUrl;
  dataForm.bookSize = res.url.size;
  // 【新增】清空 fileList，确保下次可重新上传
  fileList.value = [];

  ElMessage.success({
    message: t("prompt.success") || "上传成功",
    duration: 500
  });
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
};
// 上传错误处理
const uploadErrorHandle = (error: any) => {
  console.error("上传失败:", error);
  ElMessage.error("图片上传失败，请重试");
};
const delBook = () => {
  baseService.get(`/noc/nocsamplebook/deleteNew/${dataForm.id}`).then((res) => {
    if (res.code == 0) {
      ElMessage.success({
        message: t("prompt.success") || "删除成功",
        duration: 500
      });
      //刷新
      popupDel.value = false;
      refreshDataList();
    }
  });
};
const VoildBook = () => {
  baseService.get(`/noc/nocsamplebook/voildBook/${dataForm.id}`).then((res) => {
    if (res.code == 0) {
      ElMessage.success({
        message: t("prompt.success") || "操作成功",
        duration: 500
      });
      //刷新
      popupVoild.value = false;
      refreshDataList();
    }
  });
};
// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value?.validate(async (valid: any) => {
    if (!valid) return;
  if (!dataForm.id) {
    baseService.post("/noc/nocsamplebook/add", dataForm).then((res) => {
      if (res.code == 0) {
        ElMessage.success({
          message: t("prompt.success") || "保存成功",
          duration: 500
        });
        //刷新
        popupAdd.value = false;
        refreshDataList();
      }
    });
  
  } else {
    baseService.post("/noc/nocsamplebook/updateNew", dataForm).then((res) => {
      if (res.code == 0) {
        ElMessage.success({
          message: t("prompt.success") || "保存成功",
          duration: 500
        });
        //刷新
        popupAdd.value = false;
        refreshDataList();
      }
    });
  }
});
};

const addBook = () => {
  popupAdd.value = true;
  dataForm.id = "";
  dataForm.bookName = "";
  dataForm.bookUrl = "";
  dataForm.imgUrl = "";
  dataForm.bookSize = "";
};
const handleView = (index: number, row: User) => {
  popupInfo.value = true;
  dataForm.id = row.id;
  dataForm.bookName = row.bookName;
  dataForm.bookUrl = row.bookUrl;
  dataForm.imgUrl = row.imgUrl;
  dataForm.bookSize = row.size;
};
const handleEdit = (index: number, row: User) => {
  popupAdd.value = true;
  dataForm.id = row.id;
  dataForm.bookName = row.bookName;
  dataForm.bookUrl = row.bookUrl;
  dataForm.imgUrl = row.imgUrl;
  dataForm.bookSize = row.size;
};
const handleVoild = (index: number, row: User) => {
  popupVoild.value = true;
  dataForm.id = row.id;
  // if(row.ifValid == 0){
  //   visible.value = false // 上架
  // }else{
  //   visible.value = true  // 下架
  // }
  console.log(index, row);
};
const handleDelete = (index: number, row: User) => {
  console.log(index, row);
  popupDel.value = true;
  dataForm.id = row.id;
};

// 组件挂载时执行初始化操作
onMounted(() => {
  console.log("买家客户列表页面已加载");
});
onActivated(() => {
  console.log("页面已显示");
  uploadUrl.value = `${app.api}/sys/oss/uploadPDF`;
});
defineExpose({});
// 获取分类列表
const getClassList = () => {
  baseService
    .get("/noc/nocsamplebook/list")
    .then((res) => {
      // 确保数据结构符合级联选择器要求
      state.dataList = res.data;
    })
    .catch((error) => {
      console.error("获取分类数据出错:", error);
      ElMessage.error("获取分类数据出错");
    });
};
//刷新数据
const refreshDataList = () => {
  state.refreshDataList();
};
</script>
<style lang="less">
.picture-book-page {
  width: 100%;
  height: 100%;
  // background: url("@/assets/images/bug_ba.png") no-repeat top left;
  // background-size: 100% auto;
  font-family: "Microsoft YaHei";
  min-height: 100vh;
  padding: 0 12px;
  box-sizing: border-box;
  .book_top {
    width: 100%;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    // border-bottom: 1px solid rgba(168, 171, 178, 1);
    margin-bottom: 22px;

    .book_top_name {
      // font-size: 24px;
      // font-weight: 700;
      // letter-spacing: 0px;
      // line-height: 34.75px;
      // color: rgb(0, 0, 0);
      // margin-right: 22px;
    }

    .book_top_add {
      width: 100px;
      background-color: rgb(22, 119, 255);
      // color: rgba(16, 98, 202, 1);
    }
  }

  .table_box {
    .shanchu {
      color: rgb(245, 108, 108);
    }
  }

  .add_book {
    width: 100vw;
    height: 100vh;
    z-index: 999;
    opacity: 1;
    background: rgba(56, 56, 56, 0.5);
    position: fixed;
    top: 0;
    left: 0;

    display: flex;
    align-items: center;
    justify-content: center;
    .pop_up {
      width: 460px;
      height: 386px;
      background: rgba(255, 255, 255, 1);
      position: relative;
      .pop_up_top {
        width: 100%;
        height: 52px;
        position: relative;
        // padding-top: 16px;
        // box-sizing: border-box;
        display: flex;
        align-items: center;
        // background-color: rgba(228, 242, 255, 1);
        // justify-content: center;

        // background: url("@/assets/images/infoBack.png") no-repeat top left;
        // background-size: 100% auto;
        // .pop_up_left {
        //   width: 100px;
        //   height: 3px;
        //   border-radius: 2px;
        //   background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));
        // }
        .pop_up_name {
          margin: 0 20px;
          font-size: 18px;
          font-weight: 400;
          letter-spacing: 0px;
          line-height: 38.4px;
          color: rgb(0, 0, 0);
        }
        // .pop_up_right {
        //   width: 100px;
        //   height: 3px;
        //   border-radius: 2px;
        //   background: linear-gradient(to right, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0));
        // }
        .top_right {
          position: absolute;
          top: 20px;
          right: 16px;
          width: 14px;
          height: 14.45px;
          cursor: pointer;
          // color: rgb(0, 0, 0);
          .el-icon {
            color: rgb(139, 139, 139);
            font-size: 20px;
          }
          .close_icon {
            width: 14px;
          }
        }
      }

      .pop_up_info {
        display: flex;
        flex-wrap: wrap;
        padding: 35px 0 0 0px;
        box-sizing: border-box;
        position: relative;
        height: 300px;
        .icon {
          width: 80px;
        }

        .uploaded-image {
          width: 80px;
          height: 80px;
        }
      }
      .operation {
        position: absolute;
        bottom: 0px;
        right: 48px;
      }

      .el-upload-list__item-file-name {
        width: 80px;
      }
    }
    .pop_up_del {
      width: 420px;
      height: 140px;
      border-radius: 4px;
      .pop_up_del_top {
        width: 420px;
        height: 50px;
        // background: rgba(228, 242, 255, 1);
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        font-weight: 500;
        letter-spacing: 0px;
        line-height: 20.27px;
        color: rgba(0, 0, 0, 1);
        padding: 0 18px 0 35px;
        box-sizing: border-box;

        .top_right {
          font-size: 20px;
          color: rgba(51, 51, 51, 1);
        }
      }
      .pop_up_del_info {
        padding: 10px 0 0 35px;
        box-sizing: border-box;
        .del_info {
          display: flex;
          align-items: center;
          .del_info_icon {
            font-size: 24px;
            color: #e6a23c;
            margin-right: 12px;
          }
          .close_icon {
            width: 19px;
            margin-right: 8px;
          }
        }
        .operation {
          bottom: 10px;
          right: 18px;
        }
      }
    }
  }
}
</style>
